package com.mqtt.nettymqtt.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 上下文工具类
 * @author ln
 * @Description: ${todo}
 * @date 2020/12/4
 */
@Component
public  class ContextUtil implements ApplicationContextAware {


    private static ApplicationContext applicationContext;



//    setApplicationContext这个方法是项目启动的时候就执行了
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(ContextUtil.applicationContext==null){
            ContextUtil.applicationContext=applicationContext;
        }
        System.out.println("========ApplicationContext配置成功========");
        System.out.println("========在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象========");
    }



    /**
     * 获取applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }

    /**
     * 通过name获取Bean
     * @param name
     * @return
     */
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz){
        System.out.println(getApplicationContext());
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及clazz返回指定的bean
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name,clazz);
    }

    public static void main(String[] args) {
        Object mqttMapper = getBean("mqttMapper");
        System.out.println(mqttMapper);
    }

}
